<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            var trap = function (height) {
                let res = 0
                /* 找出中间最高柱子 */
                let maxHeightIndex = 0
                let maxHeight = 0
                for (let i = 0; i < height.length; i++) {
                    if (height[i] > maxHeight) {
                        maxHeight = height[i]
                        maxHeightIndex = i
                    }
                }
                /* 二分 */
                let leftHeight = 0
                let rightHeight = 0
                for (let i = 0; i < maxHeightIndex; i++) {
                    //找出左侧最高柱子
                    leftHeight = Math.max(leftHeight, height[i])
                    res += leftHeight - height[i]
                }
                for (let i = height.length - 1; i > maxHeightIndex; i--) {
                    rightHeight = Math.max(rightHeight, height[i])
                    res += rightHeight - height[i]
                }
                return res
            }
        </script>
    </body>
</html>
